package com.web.util.aliyun;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.web.util.Properties;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by reeves on 2015/12/16.
 */
public class ReplaceImgURL {
    private static final Logger LOGGER = Logger.getLogger(ReplaceImgURL.class);

    //文章内图片上传到OSS
    public static String replaceImgURL(String sourceImg) throws IOException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");

        // 创建oss-client
        OSSClient ossClient = new OSSClient(OssConfig.ossConfig.getEndPoint(), OssConfig.ossConfig.getAccessKeyId(), OssConfig.ossConfig.getAccessKeySecret());

        try {
        /*根据图片URL下载图片并上传到阿里云OSS，自建文件夹*/
            URL url = new URL(sourceImg);
            URLConnection conn = url.openConnection();
            URLConnection conn2 = url.openConnection();

            HttpURLConnection httpURLConnection2 = (HttpURLConnection) conn2;
            httpURLConnection2.setConnectTimeout(3 * 1000);
            httpURLConnection2.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            InputStream imgInputStream2 = httpURLConnection2.getInputStream();

            HttpURLConnection httpURLConnection = (HttpURLConnection) conn;
            httpURLConnection.setConnectTimeout(3 * 1000);
            httpURLConnection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            InputStream imgInputStream = httpURLConnection.getInputStream();

            // 设置上传文件的一些信息
            ObjectMetadata meta = new ObjectMetadata();
            meta.setContentLength(httpURLConnection.getContentLength()); // 文件大小的信息是必需的

            // 上传文件
            Date date = new Date();
            //通过图片路径的后缀名判断图片格式是否符合阿里云的标准
            String postFix = sourceImg.substring(sourceImg.length()-3);
//            if(!postFix.equals("jpg")&&!postFix.equals("peg")&&!postFix.equals("bmp")&&!postFix.equals("png")&&!postFix.equals("ebp")){

//            }
            String upFileName = String.valueOf(date.getTime())+"."+"jpg";

            String ossFilePath = "kbApp_pageImage/" + simpleDateFormat.format(date) + upFileName;
            ossClient.putObject(OssConfig.ossConfig.getBucketName(), ossFilePath, imgInputStream, meta); // 调用接口上传图片

            imgInputStream.close();

            //判断图片是否为gif图
            byte[] bt = new byte[20];
            imgInputStream2.read(bt);
            String btString = new String(bt);
            if(btString.contains("GIF89")){
                imgInputStream2.close();
                return Properties.Aliyun_Oss_ImagePrefix + ossFilePath + "@";
            }
            imgInputStream2.close();
            return Properties.Aliyun_Oss_ImagePrefix + ossFilePath;

        }catch (Exception exception){
            LOGGER.error("上传图片到阿里云OSS失败---->>",exception);
            return sourceImg+"@";
        }
    }


    //标题图片上传到OSS
    public static String replaceTitleUrl(String imageSrc) throws IOException{
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");

        File file = new File(imageSrc);
        InputStream is = new FileInputStream(file);

        // 设置上传文件的一些信息
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(file.length()); // 文件大小的信息是必需的

        //上传文件
        Date date = new Date();
        String upFileName = String.valueOf(date.getTime())+"."+"jpg";

        String ossFilePath = "kbApp_titleImage/" + simpleDateFormat.format(date) + upFileName;

        // 创建oss-client
        OSSClient ossClient = new OSSClient(OssConfig.ossConfig.getEndPoint(), OssConfig.ossConfig.getAccessKeyId(), OssConfig.ossConfig.getAccessKeySecret());
        ossClient.putObject(OssConfig.ossConfig.getBucketName(),ossFilePath,is,meta);

        return Properties.Aliyun_Oss_ImagePrefix + ossFilePath;
    }

//    public static void main(String[] args) {
//        try {
//            String result = replaceImgURL("http://img03.store.sogou.com/net/a/04/link?appid=100520031&w=710&url=http://mmbiz.qpic.cn/mmbiz/IUG5ic0ZD4vgSpRpjCbMC7t15U2fGiaxXVbqmBd6EB00icENWo0zpfKPQfdoLodLQDG87drey1tgQb0XN1o4csNwg/0/mmbizgif?");
//            System.out.println(result);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

//    public  static  void main(String [] args){
//        String result = null;
//        try {
//            result = replaceTitleUrl("C:\\Users\\haoransun\\Desktop\\tempppp\\1449064069336.jpg");
//        } catch (IOException e) {
//            System.out.println("------------出问题了----------");
//            e.printStackTrace();
//        }
//        System.out.println(result);
//    }

}
